<?php
// +----------------------------------------------------------------------
// | 产能管理 类型服务
// +----------------------------------------------------------------------
// | 主要服务于产能管理数据处理
// +----------------------------------------------------------------------
// | 错误编码头 249xxx
// +----------------------------------------------------------------------

namespace common\service;


use common\exception\LogicException;
use common\model\CapacityPoolReportModel;
use common\model\OptionsModel;
use common\model\TenantDingtalkModel;
use common\model\TenantGroupMemberModel;
use common\model\TenantModel;
use common\model\TenantUserModel;
use common\model\UserModel;
use support\ErrorCode;
use support\SingletonTrait;

class CapacityService
{
    use SingletonTrait;

    /**
     * 写入租户钉钉配置
     * @param $data
     * @return array|bool
     * @throws \think\Exception
     */
    public function writeTenantDingTalkConfig($data)
    {
        $tenantDingtalkModel = model(TenantDingtalkModel::class);
        $resData = $tenantDingtalkModel->addItem($data);
        if (!$resData) {
            // 添加租户钉钉配置失败错误码 010
            throw_strack_exception($tenantDingtalkModel->getError(), ErrorCode::ADD_DINGTALK_CONFIG_FAILURE);
        } else {
            // 返回成功数据
            return $resData;
        }
    }

    /**
     * 获取指定租户钉钉接口配置
     * @param $tenantId
     * @return array
     */
    public function getTenantDingTalkConfig($tenantId)
    {
        $tenantDingtalkModel = model(TenantDingtalkModel::class);
        $config = $tenantDingtalkModel->where(['tenant_id' => $tenantId])->find();
        if (!empty($config)) {
            return [
                'corp_id' => $config['corp_id'],  //【必填】企业 corpId
                'app_key' => $config['app_key'],   // 【必填】应用 AppKey
                'app_secret' => $config['app_secret'],     // 【必填】应用 AppSecret
            ];
        } else {
            throw_strack_exception("No configuration data.", ErrorCode::CONFIG_NOT_EXIST);
        }
    }


    /**
     * 获取指定租户钉钉排班数据
     * @param $tenantId
     * @return array
     */
    protected function getTenantDingTalkScheduling($tenantId)
    {
        $dingTalkService = new DingTalkService();
        $dingTalkService->setConfig($this->getTenantDingTalkConfig($tenantId));
        $dingTalkService->init();
        return $dingTalkService->generateDingTalkCache();
    }


    /**
     * 修正指定租户产能表（只能修复当前时间往后的半年的）
     * @param $tenantId
     * @return array
     */
    public function reviseTenantSchedulingRecord($tenantId)
    {
        return $this->getTenantDingTalkScheduling($tenantId);
    }


    /**
     * 内部允许租户按照自己情况处理
     * 1、排班（没有钉钉排班记录则自动填满1-5产能）
     * 2、产能记录表
     * 3、每天工作时长
     */


    /**
     * 批量删除配制
     * @param int   $id         删除配制option表 Id
     * @param array $configList 配制
     * @param array $configIds  配制列表IDs
     * @return void
     */
    private function batchDelConfig(int $id, array $configList, array $configIds)
    {
        //新增记录
        if (empty($configIds)) {
            return;
        }
        //修改指定项
        foreach ($configList as &$val) {
            if (in_array($val['id'], $configIds)) {
                $val['status'] = 2;
            }
        }
        $modifyData = [];
        $modifyData['id'] = $id;
        $modifyData['config'] = $configList;

        try {
            model(OptionsModel::class)->modifyItem($modifyData);
        } catch (\Exception $e) {
            trace('删除配制失败' . PHP_EOL . format_exception_info($e), 'ERR');
        }
    }

    /**
     * 保存配制
     * @param int   $id         Id
     * @param array $configList 配制
     * @param array $data       传参
     * @return int
     */
    private function saveConfigData(int $id, array $configList, array $data)
    {
        $modifyData = [];
        $modifyData['id'] = $id;
        $modifyData['config'] = $this->getNewConfigList($configList, $data);

        try {
            model(OptionsModel::class)->modifyItem($modifyData);
        } catch (\Exception $e) {
            trace('更新团队配制失败' . PHP_EOL . format_exception_info($e), 'ERR');
        }
        return $data['id'];
    }

    /**
     * 获取修改后的--配制列表
     * @param array $configList 配制列表
     * @param array $data       新增或修改数组
     * @return array
     */
    private function getNewConfigList(array $configList, array &$data)
    {
        //修改还是新增配制
        $configId = $data['id'] ?? 0;
        //新增记录
        if (empty($configId)) {
            //取现在配制最大的id
            $idList = array_column($configList, 'id');
            $data['id'] = 1;
            if ($idList) {
                $data['id'] = max($idList) + 1;
            }
            $configList[] = $data;
        } else {
            //修改指定项
            foreach ($configList as &$val) {
                if ($val['id'] == $configId) {
                    $val = $data;
                }
            }
        }
        return $configList;
    }

    /**
     * 获取--产能配制列表
     * @param int $teamCategoryId 团队环节ID
     * @return array
     */
    public function getCapacityConfig(int $teamCategoryId = 0, int $tenantId = 0)
    {
        //查询全局--配制
        $optionInfo = model(OptionsModel::class)->where(['name' => OptionsModel::NAME_CAPACITY_CONFIG])->find();
        $configList = json_decode($optionInfo['config'], true);

        //查询租户是否有配制
        $tenantConfig = [];
        if ($tenantId) {
            $tenantConfig = model(TenantModel::class)->where(['id' => $tenantId])->value('capacity_config');
            if ($tenantConfig) {
                $tenantConfig = json_decode($tenantConfig, true);
                $tenantConfig = array_column($tenantConfig, null, 'id');
            }
        }

        //过滤---配制
        $list = [];
        $i = 0;
        foreach ($configList as $val) {
            //过滤 已删除
            if ($val['status'] != 1) {
                continue;
            }
            //租户是否有配制
            if ($tenantConfig) {
                $val['default_capacity_num'] = $tenantConfig[$val['id']]['default_capacity_num'] ?? $val['default_capacity_num'];
            }
            //通过团队环节ID--指定环节的产能配制
            if ($teamCategoryId) {
                if ($val['team_category_id'] != $teamCategoryId) continue;
            }
            $list[$i] = $val;
            $i++;
        }

        $result = [];
        $result['id'] = $optionInfo['id'] ?? 0;
        $result['list'] = $list;
        return $result;
    }

    /**
     * 删除产能配制
     * @param string $configIds 产能配制IDs
     * @return int
     */
    public function delCapacityConfig(string $configIds)
    {
        //获取现有配制
        $configInfo = $this->getCapacityConfig();
        //判断
        $configIds = explode(',', $configIds);
        //判断是否被使用
        $has = model(TenantUserModel::class)->where(['tenant_position_id' => ['in', $configIds]])->field('id')->find();
        if ($has) {
            throw new LogicException("This position is currently in use and cannot be deleted", ErrorCode::POSITION_USE_NOT_DEL);
        }
        //修改配制
        $this->batchDelConfig($configInfo['id'], $configInfo['list'], $configIds);

        return 1;
    }

    /**
     * 保存产能配制
     * @param array $data
     * @return int
     */
    public function saveCapacityConfig(array $data)
    {
        //获取现有配制
        $capacityInfo = $this->getCapacityConfig();
        //判断参数
        $this->checkCapacityConfig($capacityInfo['list'], $data);
        //修改配制
        return $this->saveConfigData($capacityInfo['id'], $capacityInfo['list'], $data);
    }


    /**
     * 检查团队配制---参数
     * @param array $configList 配制
     * @param array $data       传参
     * @return void
     */
    private function checkCapacityConfig(array $configList, array $data)
    {
        $id = $data['id'] ?? 0;
        //判断名称是否重复
        if (empty($configList)) {
            return;
        }
        $configList = array_filter($configList, function ($tmp) {
            return $tmp['status'] = 1;
        });
        foreach ($configList as $val) {
            if ($val['name'] == $data['name'] && $val['id'] != $id) {
                throw new LogicException("Duplicate position name", ErrorCode::POSITION_NAME_REPEAT);
            }
        }
    }


    /**
     * 获取产能配制列表
     * @param int $teamCategoryId 团队环节ID
     * @param int $tenantId       租户ID
     * @return mixed
     */
    public function getCapacityConfigList(int $teamCategoryId, int $tenantId)
    {
        //获取现有配制
        $teamInfo = $this->getCapacityConfig($teamCategoryId, $tenantId);
        //整理数组
        return $teamInfo['list'];
    }

    /**
     * 保存租户--产能
     * @param array $data
     * @return int
     */
    public function saveTenantCapacity(array $data)
    {
        //获取全局配制
        $capacityInfo = $this->getCapacityConfig();
        $configList = $capacityInfo['list'];
        //判断参数
        $this->checkTenantCapacityConfig($configList, $data);

        //修改配制
        return $this->saveTenantConfigData($data['tenant_id'], $data);
    }

    /**
     * 检查产能配制---参数
     * @param array $configList 全局配制
     * @param array $data       传参
     * @return void
     */
    private function checkTenantCapacityConfig(array $configList, array $data)
    {
        $id = $data['id'] ?? 0;
        //判断名称是否重复
        if (empty($configList)) {
            return;
        }
        $configList = array_filter($configList, function ($tmp) {
            return $tmp['status'] = 1;
        });
        foreach ($configList as $val) {
            if ($val['default_capacity_num'] > $data['default_capacity_num'] && $val['id'] == $id) {
                throw new LogicException("The production capacity value cannot be less than the default value", ErrorCode::CAPACITY_NUM_ERROR);
            }
        }
    }

    /**
     * 保存配制
     * @param int   $tenantId 租户Id
     * @param array $data     传参
     * @return int
     */
    private function saveTenantConfigData(int $tenantId, array $data)
    {
        //查询租户是否已有配制
        $tenantConfig = model(TenantModel::class)->where(['id' => $tenantId])->value('capacity_config');
        $configList = json_decode($tenantConfig, true);

        //修改指定项
        $hasOne = $i = 0;
        if ($configList) {
            foreach ($configList as &$val) {
                if ($val['id'] == $data['id']) {
                    $val['default_capacity_num'] = $data['default_capacity_num'];
                    $hasOne = 1;
                }
                $i++;
            }
        }
        //新增
        if (!$hasOne) {
            $configList[$i]['id'] = $data['id'];
            $configList[$i]['default_capacity_num'] = $data['default_capacity_num'];
        }

        $modifyData = [];
        $modifyData['id'] = $tenantId;
        $modifyData['capacity_config'] = json_encode($configList);
        try {
            model(TenantModel::class)->modifyItem($modifyData);
        } catch (\Exception $e) {
            trace('更新产能配制失败' . PHP_EOL . format_exception_info($e), 'ERR');
        }
        return $data['id'];
    }

    /**
     * 同步产能统计
     * @param int    $tenantId         租户ID
     * @param array  $userIds          用户ID列表
     * @param string $tenantPositionId 岗位ID
     * @return int
     */
    public function syncCapacityPoolData(int $tenantId, array $userIds, string $tenantPositionId)
    {
        //先删除已有用户--产能统计
        foreach ($userIds as $userId) {
            $this->delUserCapacityPool($userId);
        }

        //多个岗位不统计产能
        if (is_numeric($tenantPositionId)) {
            $this->updateCapacityPoolData($tenantId, $tenantPositionId);
        }
        return 1;
    }

    /**
     * 更新产能统计
     * @param int $tenantId         租户ID
     * @param int $tenantPositionId 岗位ID
     * @return int
     */
    public function updateCapacityPoolData(int $tenantId, int $tenantPositionId)
    {
        if (empty($tenantPositionId)) {
            return 0;
        }
        //获取产能配制---岗位列表
        $capacityInfo = $this->getCapacityConfig(0, $tenantId);
        if (empty($capacityInfo['list'])) {
            return 0;
        }
        $positionList = array_column($capacityInfo['list'], null, 'id');
        $teamCategoryId = $positionList[$tenantPositionId]['team_category_id'] ?? 0;

        //统计月份
        $capacityReportModel = model(CapacityPoolReportModel::class);
        $reportMonth = strtotime(date('Y-m-01'));
        //查询用户ID--条件---用户状态--岗位
        $where = [];
        $where['user.is_system'] = UserModel::IS_SYSTEM_NO;
        $where['user.active'] = 1;
        $where['tenant_user.tenant_id'] = $tenantId;
        $where['tenant_user.tenant_position_id'] = $tenantPositionId;

        $userIds = model(TenantUserModel::class)
            ->join("user ON user.id = tenant_user.user_id")
            ->field('user_id')
            ->where($where)
            ->column('user_id');
        //组装数组
        $addData = [
            'report_month' => $reportMonth,
            'tenant_id' => $tenantId,
            'capacity_id' => $tenantPositionId,
            'team_category_id' => $teamCategoryId,
            'type' => CapacityPoolReportModel::TYPE_AUTO,
        ];
        //查询是否已有记录
        $hasInfo = $capacityReportModel->field('id')->where($addData)->find();
        //判断修改还是新增
        $addData['desc'] = implode(',', $userIds);
        $addData['updated'] = time();
        if (empty($hasInfo)) {
            $capacityReportModel->add($addData);
        } else {
            $capacityReportModel->where(['id' => $hasInfo['id']])->save($addData);
        }
        return 1;
    }

    /**
     * 删除--用户产能统计
     * @param int $userId
     * @return void
     */
    public function delUserCapacityPool(int $userId)
    {
        //统计月份
        $capacityReportModel = model(CapacityPoolReportModel::class);
        $reportMonth = strtotime(date('Y-m-01'));

        //查询用户是否--已有岗位--产能统计
        $condition = [
            'report_month' => $reportMonth,
            'desc' => ['FIND_IN_SET', $userId],
            'type' => CapacityPoolReportModel::TYPE_AUTO,
        ];
        $hasInfo = $capacityReportModel->field('id,desc')->where($condition)->find();
        if ($hasInfo) {
            $userList = explode(',', $hasInfo['desc']);
            //删除这个用户的统计数据
            $userList = array_diff($userList, [$userId]);
            if ($userList) {
                $capacityReportModel->where(['id' => $hasInfo['id']])->save(['desc' => implode(',', $userList)]);
            } else {
                $capacityReportModel->where(['id' => $hasInfo['id']])->delete();
            }
        }
    }

    /**
     * 产能导入
     * @param array $importCapacityData 导入的数据
     * @param int   $tenantId 租户ID
     * @return int
     */
    public function importCapacity(array $importCapacityData, int $tenantId)
    {
        //检查数据
        $importCapacityData = $this->checkImportCapacityData($importCapacityData, $tenantId);
        try {
            //循环--插入-更新数据
            $capacityReportModel = model(CapacityPoolReportModel::class);
            foreach ($importCapacityData as $val) {
                foreach ($val['time_list'] as $time) {
                    $condition = [
                        'tenant_id' => $val['tenant_id'],
                        'team_category_id' => $val['team_category_id'],
                        'report_month' => $time['report_month'],
                        'type' => CapacityPoolReportModel::TYPE_AUTO,
                    ];
                    //查询是否已有记录
                    $hasInfo = $capacityReportModel->field('id')->where($condition)->find();
                    //判断修改还是新增
                    $addData = $condition;
                    $addData['capacity_num'] = $time['capacity_num'];
                    $addData['updated'] = time();
                    if ($hasInfo) {
                        $capacityReportModel->where(['id' => $hasInfo['id']])->save($addData);
                    } else {
                        $capacityReportModel->add($addData);
                    }
                }
            }
        } catch (\Exception $e) {
            throw new LogicException("文件内容有误，请核对", ErrorCode::TENANT_NAME_ERROR);
        }
        return 1;
    }

    /**
     * 产能锁定
     * @param array $data 多个一起锁定
     * @return int
     */
    public function lockCapacity(array $data)
    {
        //检查数据
        $this->checkLockCapacityData($data);

        $capacityReportModel = model(CapacityPoolReportModel::class);
        foreach ($data as $val) {
            //循环--插入-更新数据
            $condition = [
                'tenant_id' => $val['tenant_id'],
                'team_category_id' => $val['team_category_id'],
                'report_month' => $val['report_month'],
                'project_id' => $val['project_id'],
                'attribute' => $val['attribute'] ?? '',
                'type' => CapacityPoolReportModel::TYPE_LOCK,
            ];
            //查询是否已有记录
            $hasInfo = $capacityReportModel->field('id')->where($condition)->find();
            //判断修改还是新增
            $addData = $condition;
            $addData['capacity_num'] = $val['capacity_num'];
            $addData['updated'] = time();
            if (empty($hasInfo)) {
                //新增数据
                $capacityReportModel->add($addData);
            } else {
                $capacityReportModel->where(['id' => $hasInfo['id']])->save($addData);
            }
        }
        return 1;
    }


    /**
     * 保存--解决方案
     * @param int    $teamCategoryId 团队环节ID
     * @param int    $reportMonth    月分
     * @param int    $projectId      项目ID
     * @param string $desc           方案json
     * @return int
     */
    public function saveCapacityPlan(int $teamCategoryId, int $reportMonth, int $projectId, string $desc)
    {
        //检查数据
        $capacityReportModel = model(CapacityPoolReportModel::class);
        //更新数据
        $condition = [
            'team_category_id' => $teamCategoryId,
            'report_month' => $reportMonth,
            'project_id' => $projectId,
            'type' => CapacityPoolReportModel::TYPE_CAPACITY_PLAN,
        ];
        //查询是否已有记录
        $hasInfo = $capacityReportModel->field('id')->where($condition)->find();
        //判断修改还是新增
        $addData = $condition;
        $addData['desc'] = $desc;
        $addData['updated'] = time();
        if (empty($hasInfo)) {
            //新增数据
            $capacityReportModel->add($addData);
        } else {
            $capacityReportModel->where(['id' => $hasInfo['id']])->save($addData);
        }
        return 1;
    }

    /**
     * 判断产能锁定数据
     * @param array $list
     * @return void
     */
    private function checkLockCapacityData(array $list)
    {
        $feild = "SUM(capacity_num) as capacity_num";
        //判断产能
        foreach ($list as $val) {
            if (!isset($val['tenant_id']) || !isset($val['team_category_id']) || !isset($val['report_month']) || !isset($val['capacity_num'])) {
                throw new LogicException("Parameter error", ErrorCode::REQUEST_PARAM_ERROR);
            }
            //循环--插入-更新数据
            $condition = [
                'tenant_id' => $val['tenant_id'],
                'team_category_id' => $val['team_category_id'],
                'type' => CapacityPoolReportModel::TYPE_AUTO,
            ];
            //获取总产能
            $capacityTotal = model(CapacityPoolReportModel::class)->field($feild)->where($condition)->find();
            if (empty($capacityTotal['capacity_num'])) {
                throw new LogicException("剩余产能不足", ErrorCode::INSUFFICIENT_CAPACITY_NUM);
            }
            //获取锁定的产能
            $condition['type'] = CapacityPoolReportModel::TYPE_LOCK;
            $condition['report_month'] = $val['report_month'];
            //
            $lockCapacity = model(CapacityPoolReportModel::class)->field($feild)->where($condition)->find();
            $remainingNum = $capacityTotal['capacity_num'] -  $lockCapacity['capacity_num'];

            if ($remainingNum < $val['capacity_num']) {
                throw new LogicException("剩余产能不足", ErrorCode::INSUFFICIENT_CAPACITY_NUM);
            }
        }
    }

    /**
     * 检查产能导入数据
     * @param array $list 导入的数据
     * @param int   $tenantId 租户ID
     * @return array
     */
    private function checkImportCapacityData(array $list, int $tenantId)
    {
        //先获取集团ID列表
        $tenantGroupList = model(TenantGroupMemberModel::class)->alias('tgm')
            ->join('tenant_group ON tgm.tenant_group_id = tenant_group.id')
            ->field('tgm.tenant_group_id')
            ->where(['tgm.tenant_id'=>$tenantId])
            ->column('tenant_group_id');
        if (empty($tenantGroupList)) {
            throw new LogicException("没有加入团队", ErrorCode::TENANT_IMPORT_ERROR);
        }
        //集团ID--获取租户列表
        $tenantList = model(TenantGroupMemberModel::class)->alias('tgm')
            ->join('tenant ON tgm.tenant_id = tenant.id')
            ->field('tenant.id,tenant.name')
            ->where(['tgm.tenant_group_id'=>['in', $tenantGroupList]])
            ->select();
        $tenantList = array_column($tenantList, null, 'name');

        //循环
        foreach ($list as &$val) {
            $tenantId = $tenantList[$val['tenant_name']]['id'] ?? 0;

            if (empty($tenantId)) {
                throw new LogicException("供应商名错误或没有相应供应商权限：" . $val['tenant_name'], 33);
            }
            if (!isset($val['team_category_id'])) {
                throw new LogicException("环节名错误：" . $val['team_category_name'], 22);
            }

            $val['tenant_id'] = $tenantId;
        }
        return $list;
    }

    /**
     * 获取产能报表
     * @param array $param 条件
     * @return array
     */
    public function getCapacityReportList(array $param)
    {
        //获取查询条件
        $where = $this->buildCapacityReportCondition($param);
        //查询字段
        $field = "cpr.id,cpr.report_month,cpr.project_id,cpr.tenant_id,cpr.type,cpr.team_category_id,cpr.capacity_num,cpr.capacity_id,cpr.desc,t.name as tenant_name, t.nature as tenant_nature";
        //查询产能统计列表
        $list = model(CapacityPoolReportModel::class)->alias('cpr')
            ->join("tenant t ON cpr.tenant_id = t.id", 'left')
            ->field($field)
            ->where($where)
            ->select();

        if (empty($list)) {
            return [];
        }
        //整理返回数据
        foreach ($list as &$val) {
            //获取每月产能
            $val['capacity_num'] = $this->getTenantCapacityNum($val, $val['capacity_num']);
        }
        return $list;
    }


    /**
     * 构建---产能查询条件
     * @param array $param
     * @return array
     */
    private function buildCapacityReportCondition(array $param)
    {
        $where = [];
        //查询环节
        $where['cpr.team_category_id'] = ['in', explode(',', $param['team_category_id'])];
        $where['cpr.report_month'] = ['BETWEEN', [$param['start_time'], $param['end_time']]];
        //集团查询
        if (!empty($param['tenant_group_ids'])) {
            //集团ID
            $tenantIds = model(TenantGroupMemberModel::class)
                ->field('tenant_id')
                ->where(['tenant_group_id' => ['IN', explode(',', $param['tenant_group_ids'])]])
                ->column('tenant_id');

            if (empty($tenantIds)) {
                return [];
            }
            $where['cpr.tenant_id'] = ['in', $tenantIds];
        }
        //租户
        if (!empty($param['tenant_id'])) {
            $where['cpr.tenant_id'] = $param['tenant_id'];
        }
        //供应商性质
        if (!empty($param['nature'])) {
            $where['t.nature'] = $param['nature'];
        }
        //项目ID
        if (!empty($param['project_id'])) {
            $where['cpr.project_id'] = $param['project_id'];
        }
        //锁定的产能type
        if (!empty($param['type'])) {
            $where['cpr.type'] = ['in', explode(',', $param['type'])];
        }
        return $where;
    }

    /**
     * 获取每月产能
     * @param array $info        详情
     * @param int   $capacityNum 产能
     * @return int
     */
    private function getTenantCapacityNum(array $info, int $capacityNum, int $crontab = 0)
    {
        $month = strtotime(date('Y-m-01'));
        //判断产能ID--是否为空
        if (empty($info['capacity_id']) || empty($info['tenant_id'])) {
            return $capacityNum;
        }
        //判断月份--是否当前月份
        if ($month != $info['report_month'] && empty($crontab)) {
            return $capacityNum;
        }
        //判断类型是否---自动生成
        if (CapacityPoolReportModel::TYPE_AUTO != $info['type']) {
            return $capacityNum;
        }

        //获取岗位--产能值
        $capacityInfo = $this->getCapacityConfig(0, $info['tenant_id']);
        $capacityList = array_column($capacityInfo['list'], null, 'id');
        $defaultCapacityNum = $capacityList[$info['capacity_id']]['default_capacity_num'] ?? 0;
        //计算产能 = 人 * 产能值
        $defaultCapacityNum = $defaultCapacityNum * count(explode(',', $info['desc']));

        //更新产能
        if ($defaultCapacityNum > $capacityNum) {
            model(CapacityPoolReportModel::class)->where(['id'=>$info['id']])->save(['capacity_num'=>$defaultCapacityNum]);
            return $defaultCapacityNum;
        }
        return $capacityNum;
    }

    /**
     * 月未更产能值
     * @return int
     */
    public function fixTenantCapacityNum()
    {
        //判断时间
        $judgeTime = strtotime('-1 day');
        if (date('Ymd', $judgeTime) == date('Ymt', $judgeTime)) {
            return 1;
        }
        $where = [];
        //查询条件
        $where['report_month'] = strtotime(date('Y-m-01', $judgeTime));
        $where['type'] = CapacityPoolReportModel::TYPE_AUTO;

        //查询产能统计列表
        $list = model(CapacityPoolReportModel::class)
            ->field('id,report_month,tenant_id,type,capacity_num,capacity_id,desc')
            ->where($where)
            ->select();

        if (empty($list)) {
            return 1;
        }
        //更新产能
        $saveData = [];
        foreach ($list as $val) {
            $saveData[] = ['id' => $val['id'], 'capacity_num' => $this->getTenantCapacityNum($val, $val['capacity_num'], 1)];
        }
        model(CapacityPoolReportModel::class)->saveAll($saveData);
        return 1;
    }

}
